package com.heima.controller.resident;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.context.ResidentContext;
import com.heima.domain.dto.HealthDataDTO;
import com.heima.domain.po.HealthData;
import com.heima.Result;
import com.heima.domain.query.HealthDataQuery;
import com.heima.service.IHealthDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import com.heima.domain.vo.HealthDataTrendsVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.*;
import java.util.stream.Collectors;
/**
 * <p>
 * 健康数据表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-28
 */
@Tag(name = "居民健康数据接口")
@RestController
@RequestMapping("/resident")
public class HealthDataController {
    @Autowired
    private IHealthDataService healthDataService;
    @Operation(summary = "查看健康数据")
    @GetMapping("/get/health-data")
    public Result getHealthData() {
        Long userId = ResidentContext.getCurrentId();
        LocalDate beginTime = LocalDate.now();
        LocalDate endTime = LocalDate.now().plusDays(1);
        HealthData healthData = healthDataService.lambdaQuery()
                .ge(HealthData::getCreateTime, beginTime)
                .lt(HealthData::getCreateTime, endTime)
                .eq(HealthData::getUserId, userId)
                .one();
        return healthData == null ? Result.success() : Result.success(healthData);
    }
    @Operation(summary = "新增健康数据")
    @PostMapping("/add/health-data")
    public Result addHealthData(@RequestBody HealthDataDTO healthDataDTO) {
        Long userId = ResidentContext.getCurrentId();
        HealthData healthData = BeanUtil.copyProperties(healthDataDTO, HealthData.class);
        healthData.setCreateTime(LocalDateTime.now());
        healthData.setUpdateTime(LocalDateTime.now());
        healthData.setUserId(userId);
        healthDataService.save(healthData);
        return Result.success();
    }
    @Operation(summary = "更新健康数据")
    @PutMapping("/update/health-data")
    public Result updateHealthData(@RequestBody HealthDataDTO healthDataDTO) {
        HealthData healthData = BeanUtil.copyProperties(healthDataDTO, HealthData.class);
        healthData.setUpdateTime(LocalDateTime.now());
        healthDataService.updateById(healthData);
        return Result.success();
    }
    @Operation(summary = "查询本周步数、本周血糖趋势、昨晚睡眠时长、今日体重")
    @GetMapping("/get/health-data/trends")
    public Result getHealthDataTrends() {
        if(ResidentContext.getCurrentId() == null) return Result.error("请先登录");
        Long userId = ResidentContext.getCurrentId();
        LocalDate endTime = LocalDate.now().plusDays(1);  // 明天的日期
        LocalDate startTime = endTime.minusDays(7);  // 7天前的日期
        // 初始化数据列表
        Map weekSteps = new HashMap();
        Map weekBloodSugar = new HashMap();
        Double lastNightSleep = 0.0;
        Double todayWeight = 0.0;
        // 创建返回对象
        HealthDataTrendsVO trendsVO = new HealthDataTrendsVO(weekSteps, weekBloodSugar, lastNightSleep, todayWeight);
        // 查询一周内的健康数据
        LambdaQueryWrapper<HealthData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HealthData::getUserId, userId)
                .ge(HealthData::getCreateTime, startTime)
                .lt(HealthData::getCreateTime, endTime)
                .orderByAsc(HealthData::getCreateTime);
        List<HealthData> healthDataList = healthDataService.list(queryWrapper);
        if(healthDataList.isEmpty()) return Result.success(trendsVO); // 如果没有数据，直接返回空的趋势VO

            // 处理本周步数和血糖趋势
       for(HealthData healthData : healthDataList) {
           Long steps = healthData.getSteps();
              Double bloodSugar = healthData.getBloodSugar();
             if(steps != null) {
                 weekSteps.put(healthData.getCreateTime().toLocalDate(), steps);
             } else {
                    weekSteps.put(healthData.getCreateTime().toLocalDate(), 0L); // 如果步数为null，添加0
             }
                if(bloodSugar != null) {
                    weekBloodSugar.put(healthData.getCreateTime().toLocalDate(), bloodSugar);
                } else {
                    weekBloodSugar.put(healthData.getCreateTime().toLocalDate(), 0.0); // 如果血糖为null，添加0.0
                }
       }
            // 处理昨晚睡眠时长
        Double sleepDuration = healthDataList.get(healthDataList.size() - 1).getSleepDuration();
        lastNightSleep= sleepDuration != null ? sleepDuration : 0.0; // 如果睡眠时长为null，设置为0.0
            // 处理今日体重
        Double weight = healthDataList.get(healthDataList.size() - 1).getWeight();
        todayWeight = weight != null ? weight : 0.0; // 如果体重为null，设置为0.0
        // 设置返回数据
        trendsVO.setWeekSteps(weekSteps);
        trendsVO.setWeekBloodSugar(weekBloodSugar);
        trendsVO.setLastNightSleep(lastNightSleep);
        trendsVO.setTodayWeight(todayWeight);
        return Result.success(trendsVO);
    }

    @Operation(summary = "分页查询健康数据历史记录")
    @GetMapping("/get/health-data/history")
    public Result getHealthDataHistory(HealthDataQuery healthDataQuery) {
        if(ResidentContext.getCurrentId() == null) return Result.error("请先登录");
        Long userId = ResidentContext.getCurrentId();
        LocalDateTime beginTime = healthDataQuery.getBeginTime();
        LocalDateTime endTime = healthDataQuery.getEndTime();
        Integer pageNum= healthDataQuery.getPageNum();
        Integer pageSize= healthDataQuery.getPageSize();
        Page<HealthData> p = healthDataService.lambdaQuery()
                .eq(HealthData::getUserId, userId)
                .ge(beginTime != null, HealthData::getCreateTime, beginTime)
                .le(endTime != null, HealthData::getCreateTime, endTime)
                .orderByDesc(HealthData::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
        List<HealthData> records = p.getRecords();
        if(records.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        return Result.success(records);
    }
}
